package com.zzhua.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.SameSiteCookies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class TestController {

    @Value("${server.port}")
    private String port;

    @Autowired
    private HttpServletRequest request;
    @Autowired(required = false)
    private HttpServletResponse response;


    @RequestMapping("/test01")
    public String test01() {
        System.out.println("test01-out");
        System.err.println("test01-err");
        return "test01";
    }


    @RequestMapping("/test02")
    public String test02() {
        log.debug("test02-debug");
        log.info("test02-info");
        log.warn("test02-warn");
        log.error("test02-error");
        return "test02";
    }

    @RequestMapping("/test03")
    public String test03() {
        log.info("Host: {}", request.getHeader("Host"));
        log.info("X-Real-IP: {}", request.getHeader("X-Real-IP"));
        log.info("X-Forwarded-For: {}", request.getHeader("X-Forwarded-For"));
        log.info("request.getRemoteAddr(): {}", request.getRemoteAddr());
        return "test03";
    }

    @RequestMapping("/setCookie")
    public Object setCookie() {
        Map<String, Object> headers = getAllHeaders();
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.info("创建session...");
            session = request.getSession(true);
            log.info("新session: {}", session.getId());
        } else {
            log.info("已存在session: {}", session.getId());
        }

        /*
        request可获取所有的cookie,
        response可以添加cookie,每添加1个cookie,都会设置1个Set-cookie头,每次setHeader("Set-Cookie","")就会将之前的Set-Cookie都给覆盖掉

        浏览器每次都会携带能够应用到当前的cookie，并且以Cookie作为请求头

        */

        Cookie cookie1 = new Cookie("name","lsl");
        response.addCookie(cookie1);
        Cookie cookie2 = new Cookie("age","18");
        response.addCookie(cookie2);

        /*
        上面2个都不会写给客户端, 会被下面的setHeader给覆盖掉,
        下面会写出2个Set-Cookie头给客户端,
        下次客户端时会携带1个Cookie头, 里面包含下面的2个值
        */

        /*
        第1次request.getSession(true)时就会调用response.addCookie(..)方法, 默认写给客户端1个JSESSIONID的Cookie, 也即写1个Set-Cookie给客户端,
        */

        /*ResponseCookie cookie = ResponseCookie.from("JSESSIONID", session.getId())
                // 必须是https
                .sameSite(SameSiteCookies.NONE.getValue())
                .httpOnly(true)
                // .secure(true)
                .maxAge(-1)
                .path("/")
                .build();
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());*/
        /* 如果调用这里, 默认就会添加2个JSESSIONID给客户端, 即2个Set-Cookie头, key都是JSESSIONID */
        // response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());

        Cookie cookie3 = new Cookie("addr","beijing");
        response.addCookie(cookie3);



        return headers;
    }

    @RequestMapping("/getCookie")
    public Object getCookie() {
        HttpSession session = request.getSession(false);

        if (session != null) {
            log.info("session存在");
        } else {
            log.info("session不存在");
        }
        return getAllHeaders();
    }

    private Map<String, Object> getAllHeaders() {
        HashMap<String, Object> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }

    @RequestMapping("/docker")
    public String helloDocker() {
        return "hello docker" + "\t" + port + "\t" + UUID.randomUUID().toString().replace("-", "");
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "服务端口号：" + "\t" + port + "\t" + UUID.randomUUID().toString().replace("-", "");
    }
}
